//
//  WJSignatureHistoryViewController.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/26.
//

import UIKit
import SnapKit

protocol WJSignatureHistoryViewControllerDelegate: AnyObject {
    func useHistorySignature(controller: WJSignatureHistoryViewController, historyModel: WJSignatureHistoryModel)
    func addNewSignature(controller: WJSignatureHistoryViewController)
}

class WJSignatureHistoryViewController: WJBaseViewViewController {
    
    weak var delegate: WJSignatureHistoryViewControllerDelegate? = nil
    
    // 顶部透明区域高度常量
    private let transparentTopHeight: CGFloat = 172 - safeAreaTop
    
    // 签名数据数组
    private var signatures: [WJSignatureHistoryModel] = []
    
    var selectedHistoryModel: WJSignatureHistoryModel? = nil
    // 用于展示签名的集合视图
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        let width = (view.bounds.width - 35) / 2
        let height = width + 40 // 图片高度+文字高度
        layout.itemSize = CGSize(width: width, height: height)
        layout.minimumInteritemSpacing = 11
        layout.minimumLineSpacing = 11
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .clear
        cv.register(WJSignatureHistoryCell.self, forCellWithReuseIdentifier: "WJSignatureHistoryCell")
        cv.dataSource = self
        cv.delegate = self
        cv.allowsSelection = true
        
        return cv
    }()
    
    private lazy var addNewButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Add new", for: .normal)
        button.setTitleColor(UIColor(hex: "#FFFFFF"), for: .normal)
        button.backgroundColor = UIColor(hex: "#1F87F6")
        button.layer.cornerRadius = 16
        button.addTarget(self, action: #selector(addNewSignature), for: .touchUpInside)
        return button
    }()
    
    private lazy var createButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Create", for: .normal)
        button.setTitleColor(UIColor(hex: "#FFFFFF"), for: .normal)
        button.backgroundColor = UIColor(hex: "#1F87F6")
        button.layer.cornerRadius = 22
        button.addTarget(self, action: #selector(createSignature), for: .touchUpInside)
        return button
    }()
    
    private lazy var topBarImgView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .scaleAspectFit
        iv.image = UIImage(named: "top_dismiss")
        iv.isUserInteractionEnabled = true
        return iv
    }()
    
    // 标题标签
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = "Signature"
        label.font = UIFont.montserratMedium(16)
        label.textColor = UIColor(hex: "#121212")
        return label
    }()
    
    // 内容容器视图（用于承载所有非透明区域内容）
    private lazy var contentContainer: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex: "#FFFFFF")
        view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner] // 顶部两角圆角
        view.layer.cornerRadius = 24
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .clear
        setupSubviews()
        setupConstraints()
        loadLocalSignatures()
    }
    
    private func loadLocalSignatures() {
        do {
            self.signatures = try WJSignatureHistoryModel.findAllTyped().sorted(by: { model1, model2 in
                model1.createdDate > model2.createdDate
            })
            
            if signatures.isEmpty {
                wjUpdateState(.noData)
            } else {
                wjUpdateState(.finished)
            }
            
            self.collectionView.reloadData()
        } catch {
            print("加载签名数据失败: \(error)")
        }
    }

    private func setupSubviews() {
        // 先添加容器视图，再添加其他子视图到容器中
        view.addSubview(contentContainer)
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapTopBarAction(_:)))
        topBarImgView.addGestureRecognizer(tapGesture)
        contentContainer.addSubview(topBarImgView)
        contentContainer.addSubview(titleLabel)
        contentContainer.addSubview(addNewButton)
        contentContainer.addSubview(collectionView)
        contentContainer.addSubview(createButton)
    }
    
    private func setupConstraints() {
        contentContainer.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(transparentTopHeight)
            make.leading.trailing.bottom.equalToSuperview()
        }
        
        topBarImgView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.leading.trailing.equalToSuperview().inset(20)
            make.height.equalTo(24)
        }
        
        // 标题标签约束
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(topBarImgView.snp.bottom).offset(5) // 距离容器顶部20
            make.leading.equalToSuperview().offset(20)
            make.trailing.equalTo(addNewButton.snp.leading).offset(-5)
        }
        
        // 添加新签名按钮约束
        addNewButton.snp.makeConstraints { make in
            make.centerY.equalTo(titleLabel)
            make.trailing.equalToSuperview().offset(-20)
            make.width.equalTo(100)
            make.height.equalTo(32)
        }
        
        // 集合视图约束
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(20)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(createButton.snp.top).offset(-20)
        }
        
        // 创建按钮约束
        createButton.snp.makeConstraints { make in
            make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-20)
            make.leading.equalToSuperview().offset(50)
            make.trailing.equalToSuperview().offset(-50)
            make.height.equalTo(44)
        }
    }
    
    
    @objc func tapTopBarAction(_ tap: UITapGestureRecognizer) {
        dismiss(animated: true)
    }
    
    @objc private func addNewSignature() {
        // 跳转到添加新签名页面
        self.dismiss(animated: false) { [weak self] in
            guard let self = self else { return }
            self.delegate?.addNewSignature(controller: self)
        }
    }
    
    @objc private func createSignature() {
        guard let historyModel = selectedHistoryModel else {
            return
        }
        self.delegate?.useHistorySignature(controller: self, historyModel: historyModel)
        self.dismiss(animated: true)
    }
}

// MARK: - 集合视图数据源和代理
extension WJSignatureHistoryViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return signatures.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WJSignatureHistoryCell", for: indexPath) as! WJSignatureHistoryCell
        cell.configure(with: signatures[indexPath.item])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        signatures.forEach { $0.isSelected = false }
        // 设置当前项为选中
        let historyModel = signatures[indexPath.item]
        historyModel.isSelected = true
        // 刷新整个集合视图
        collectionView.reloadData()
        self.selectedHistoryModel = historyModel
    }
}

extension WJSignatureHistoryViewController: WJNoDataProtocol {
    var wjStateContainer: UIView {
        return self.collectionView
    }
    
    func wjFrame(for state: WJState) -> CGRect? {
        switch state {
        case .noData:
            return CGRect(x: 0, y: 76, width: view.bounds.width, height: 300)
        default:
            return nil
        }
    }
    
    func wjImage(for state: WJState) -> UIImage? {
        switch state {
        case .noData:
            return UIImage(named: "no_signed_image")
        default:
            return nil
        }
    }
    
    func wjButtonTitle(for state: WJState) -> String? {
        return nil
    }
    
    func wjTitle(for state: WJState) -> String {
        switch state {
        case .noData:
            return "No sign here yet."
        default:
            return ""
        }
    }
    
    func wjMessage(for state: WJState) -> String {
        return ""
    }
    
    func wjDidTapStateButton() {
        
    }
}
